<template>
    <div class="many-list-page">
        <div class="many-list-header">
            <div class="many-list-header-title">用户管理</div>
            <div class="many-list-btn">
                <el-button type="" @click="handleBatchDelete()"><el-icon>
                        <Delete />
                    </el-icon> 删除</el-button>
                <el-button type="primary" @click="handleAdd()"><el-icon>
                        <Plus />
                    </el-icon> 添加</el-button>
            </div>
        </div>
        <div class="many-search-box">
            <el-form :inline="true" :model="searchForm" class="demo-form-inline" ref="searchFormRef">
                <div>
                    <el-form-item label="" prop="name">
                        <el-input v-model="searchForm.username" placeholder="请输入姓名" :prefix-icon="Search"></el-input>
                    </el-form-item>

                    <el-form-item label="" prop="status">
                        <el-select v-model="searchForm.status" placeholder="状态" style="width: 130px" clearable>
                            <template #label="{ label }">
                                <span>状态: </span>
                                <span style="font-weight: bold">{{ label }}</span>
                            </template>
                            <el-option v-for="item in statusList" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="" prop="sex">
                        <el-select v-model="searchForm.sex" placeholder="性别" style="width: 100px" clearable>
                            <template #label="{ label }">
                                <span>性别: </span>
                                <span style="font-weight: bold">{{ label }}</span>
                            </template>
                            <el-option v-for="item in sexList" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                </div>
                <div>
                    <el-button @click="resetForm(searchFormRef)" text>重置</el-button>
                    <el-button @click="onQuery" text>查询</el-button>
                </div>
            </el-form>
        </div>
        <div class="many-table-area">
            <el-table :data="tableData" stripe header-row-class-name="many-table-header"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column type="index" width="55" label="序号"></el-table-column>
                <el-table-column prop="id" label="用户编码"></el-table-column>
                <el-table-column prop="username" label="姓名"></el-table-column>
                <el-table-column prop="birthday" label="出生年月"></el-table-column>
                <el-table-column prop="sexDesc" label="性别"></el-table-column>
                <el-table-column prop="statusDesc" label="状态">
                    <template #default="scope">
                        <el-tag :type="getStatusTag(scope.row.status)" disable-transitions round>
                            {{ scope.row.statusDesc }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="creator" label="创建人"></el-table-column>
                <el-table-column prop="modifier" label="修改人"></el-table-column>
                <el-table-column prop="created" label="创建时间" width="180"></el-table-column>
                <el-table-column prop="modified" label="修改时间" width="180"></el-table-column>
                <el-table-column fixed="right" label="操作" width="260">
                    <template #default="scope">
                        <el-button size="small" color="#626aef" @click="handleEdit(scope.$index, scope.row)">
                            授权
                        </el-button>
                        <el-button size="small" type="warning" @click="frozen(scope.$index, scope.row)"
                            v-if="scope.row.status !== 2">
                            {{ scope.row.status === 1 ? '解锁' : '锁定' }}
                        </el-button>
                        <el-button size="small" type="primary" @click="handleEdit(scope.$index, scope.row)">
                            编辑
                        </el-button>
                        <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="many-page-area">
            <el-pagination v-model:current-page="Page.currentPage" v-model:page-size="Page.pageSize"
                :page-sizes="Page.pageSizes" :size="Page.size" :disabled="false" :background="false"
                layout="prev, pager, next,  jumper, sizes, total" :total="Page.total">
            </el-pagination>
        </div>

        <div class="drawer">
            <el-drawer v-model="showDrawer" :show-close="false" :direction="direction" :before-close="handleClose"
                :key="drawerKey">
                <template #header="{ close, titleId, titleClass }">
                    <h4 :id="titleId" :class="titleClass">新增用户</h4>
                    <el-button @click="close">
                        <el-icon>
                            <Close />
                        </el-icon>
                        关闭
                    </el-button>
                    <el-button type="primary" @click="saveUser">
                        <el-icon>
                            <Edit />
                        </el-icon>
                        保存
                    </el-button>
                </template>

                <el-form label-position="top" label-width="auto" :model="userAddForm" :rules="addUserRules"
                    ref="userAddFormRef">
                    <el-form-item label="姓名" prop="username">
                        <el-input v-model="userAddForm.username" placeholder="请填写姓名" />
                    </el-form-item>
                    <el-form-item label="年龄" prop="birthday">
                        <el-date-picker v-model="userAddForm.birthday" type="date" placeholder="选择生日"
                            value-format="YYYY-MM-DD" />
                    </el-form-item>
                    <el-form-item label="性别" prop="sex">
                        <el-select v-model="userAddForm.sex" placeholder="请选择性别" clearable>
                            <template #label="{ label }">
                                <span>性别: </span>
                                <span style="font-weight: bold">{{ label }}</span>
                            </template>
                            <el-option v-for="item in sexList" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-form>
            </el-drawer>
        </div>
    </div>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { DrawerProps, FormInstance, FormRules } from 'element-plus'
import { Edit, Plus, Delete, Close } from '@element-plus/icons-vue'
import { ajax } from '@/api/ajax'
import api from '@/api/index'
import Many from '@/utils/many'

const searchForm = reactive({
    username: null,
    sex: null,
    status: null
});

const searchFormRef = ref<FormInstance>()

const Page = reactive({
    currentPage: 1,
    pageSize: 10,
    size: 'default',
    total: 0,
    pageSizes: [10, 20, 50, 100]
})

const sexList = [
    { label: '', value: '' },
    { label: '男', value: '1' },
    { label: '女', value: '0' },
]

const statusList = [
    { label: '', value: '' },
    { label: '正常', value: '0' },
    { label: '冻结', value: '1' },
    { label: '未验证', value: '2' },
]

interface User {
    id: number,
    username: string,
    birthday: string,
    sex: string,
    sexDesc: string,
    status: string,
    statusDesc: string,
    creator: string,
    modifier: string,
    created: string,
    modified: string
}

const tableData = ref<User[]>([])

const showDrawer = ref(false)
const direction = ref<DrawerProps['direction']>('rtl')
const multipleSelection = ref<User[]>([])

onMounted(() => {
    loadTableData();
});

const handleAdd = () => {
    showDrawer.value = true
}

const handleDelete = (index: number, row: any) => {
    console.log(index, row);
    ajax({
        url: api.userApi.delete,
        method: 'post',
        params: { ids: [row.id] }
    }).then((res) => {
        console.log("请求结果：", res);
        loadTableData();
    })
}

const handleClose = (done: any) => {
    console.log("drawer closed");
    userAddForm.id = null;
    userAddForm.username = '';
    userAddForm.birthday = '';
    userAddForm.sex = '';

    showDrawer.value = false

    setTimeout(() => {
        drawerKey.value++;
    }, 300);

    done()
}

const loadTableData = () => {
    let params = getFormData();
    ajax({
        url: api.userApi.pageList,
        method: 'post',
        params: params
    }).then((res) => {
        console.log("请求结果：", res);
        Page.total = res.data.total;
        tableData.value = res.data.records;
    })
}

const getFormData = () => {
    return {
        ...searchForm,
        size: Page.pageSize,
        current: Page.currentPage
    }
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) {
        return;
    }

    formEl.resetFields();
}

const onQuery = () => {
    loadTableData();
}

const getStatusTag = (status: number) => {
    if (status === 0) {
        return 'success'
    } else if (status === 1) {
        return 'danger'
    } else {
        return 'info'
    }
}

const handleSelectionChange = (val: User[]) => {
    console.log(val);
    multipleSelection.value = val;
}


/********************* 新增 & 编辑 ***********************/
const drawerKey = ref(0);
const userAddFormRef = ref<FormInstance>();

const userAddForm = reactive({
    id: null,
    username: '',
    birthday: '',
    sex: '',
});

const saveUser = async () => {
    if (!userAddFormRef.value) return;

    await userAddFormRef.value.validate((valid) => {
        if (!valid) {
            return;
        }

        ajax({
            url: api.userApi.save,
            method: 'post',
            params: userAddForm
        }).then((res: any) => {
            if (res.code === '0000') {
                showDrawer.value = false;
                loadTableData();
                handleClose(() => { });
            }
        });
    });
}

const addUserRules: FormRules = {
    username: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
    ],
    birthday: [
        { type: 'date', required: true, message: '请选择日期', trigger: ['blur', 'change'] },
        {
            validator: (rule: any, value: any, callback: any) => {
                if (!value) {
                    callback(new Error('请选择日期'))
                } else {
                    const eighteenYearsAgo = new Date();
                    eighteenYearsAgo.setFullYear(eighteenYearsAgo.getFullYear() - 18);
                    const selectedDate = new Date(value);
                    if (selectedDate > eighteenYearsAgo) {
                        callback(new Error('年龄不能低于18岁'));
                    } else {
                        callback();
                    }
                }
            },
            trigger: 'change'
        }
    ],
    sex: [
        { required: true, message: '性别必填', trigger: ['blur', 'change'] }
    ]
}

/*********************************** 编辑 ********************************/
const handleEdit = (index: number, row: any) => {
    console.log("编辑: ", index)
    Object.assign(userAddForm, row);
    userAddForm.sex = row.sex + '';
    showDrawer.value = true;
}

const frozen = (index: number, row: any) => {
    console.log("冻结/解冻: ", index);
    let status = row.status === 0 ? 1 : 0;
    let params = { id: row.id, status: status };

    ajax({
        url: api.userApi.frozen,
        method: 'post',
        params: params
    }).then((res) => {
        console.log("请求结果：", res);
        loadTableData();
    })
}

const handleBatchDelete = () => {
    let selected = multipleSelection.value.map((item: any) => item.id);
    if (selected.length === 0) {
        Many.notice({
            title: '',
            message: '请选择一行',
            type: 'warning',
        });
        return;
    }

    ajax({
        url: api.userApi.delete,
        method: 'post',
        params: { ids: selected }
    }).then((res) => {
        console.log("请求结果：", res);
        loadTableData();
    })
}

</script>

<style lang="css">
.demo-form-inline {
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    justify-content: space-between;
}
</style>